<?php
namespace submodule\base;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;


use submodule\models\Models;
use submodule\models\ModelsField;
use submodule\models\Module;
use common\components\Tree;
use base\YiiMobo;

class BaseModelsController extends \submodule\base\BaseSubmoduleController
{

	
	public $models;

	
	
	public function init(){
		parent::init();
	    $this->models = (object)null;
		$this->models->models_table = Models::tableName();
		$this->models->field_table = ModelsField::tableName();
		$this->models->type = isset($_REQUEST['type']) && $_REQUEST['type'] ? $_REQUEST['type'] : 'content';
		//$this->models->modelid = $_REQUEST['modelid'];
		
		//视图
		$this->models->viewFiles = [
		    'index'=> '@submodule/views/models/models_index',
		    'form'=> '@submodule/views/models/models_form',
			'api'=> '@submodule/views/models/models_api',
			'api-document'=> '@submodule/views/models/models_api-document',
		    'field'=> '@submodule/views/models/models_field',
			'field_form' => '@submodule/views/models/models_field_form',
		];
		
		$this->models->actionUrl = [
		    'index'=> $this->module->id.'/models',
		    'submodel-index'=> $this->module->id.'/index',
			'api'=> $this->module->id.'/models/api',
			'api-document'=> $this->module->id.'/models/api-document',
			'create' => $this->module->id.'/models/create',
			'update'=> $this->module->id.'/models/update',
			'batch'=> $this->module->id.'/models/batch',
			'view'=> $this->module->id.'/models/view',
			'delete'=> $this->module->id.'/models/delete',
			'status'=> $this->module->id.'/models/status',
			'update-cache'=> $this->module->id.'/models/update-cache',
			'field'=> $this->module->id.'/models/field',
			'check-tablename'=> $this->module->id.'/models/check-tablename',
			'create-field'=> $this->module->id.'/models/create-field',
			'update-field'=> $this->module->id.'/models/update-field',
			'formfield'=> $this->module->id.'/models/formfield',
			'field-batch'=> $this->module->id.'/models/field-batch',
			'field-status'=> $this->module->id.'/models/field-status',
			
			
		];

	}

	/**
	 * 获取action的url
	 */
    public function getModelsActionUrl($action, $returnUrl = true){
		$url = isset($this->models->actionUrl[$action[0]]) ? $this->models->actionUrl[$action[0]] : false;
		$url = str_replace($action[0] , $url, $action);
		if ($returnUrl){
			$url = $this->createUrl($url);
		}
		return $url;
		
	}
	/**
	 * 设置视图文件
	 */
    public function setViewFiles($views){
		foreach($views as $k=>$view){
		    $this->models->viewFiles[$k]  = $view;
		}
	}
	
	/**
	 * 获取视图文件
	 */
    public function getViewFiles($action = 'index'){
		$viewfile = isset($this->models->viewFiles[$action]) ? $this->models->viewFiles[$action] : false;
		if (!$viewfile){
			$viewfile = "@submodule/views/models/models_".$action;
		}
		return $viewfile;
		
	}
	
	/**
	* 安装模型数据表
	*/
	public function install($models, $module, $action = 'install'){
		$class = "\submodule\modules\\{$module}\components\Uninstaller";
		$Uninstaller = new $class($this);
		return $Uninstaller->$action($models, $this->models->field_table);
		
	}
	/**
	 * 添加数据库字段
     * 
	 */
    public function CreateField($model, $sql = ''){
		$model_path = $sql ? $sql : Yii::getAlias('@submodule')."/views/models/sql/model_$model->type.sql";
		$sql = file_get_contents($model_path);
        
		
		$sql = str_replace('{{%table}}', '{{%'.$model->tablename.'}}', $sql);
		$sql = str_replace('{{%models_field}}',$this->models->field_table, $sql);
		$sql = str_replace('{{%$modelid}}',$model->modelid, $sql);
		
		$sql = str_replace('{{%table_data}}', '{{%'.$model->tablename.'_data}}', $sql);
		$sql = explode(';'.PHP_EOL, $sql);
		foreach($sql as $v){
			$v = str_replace(PHP_EOL, '', $v);
		    if (!empty($v) && preg_match("/^[a-z]/i", $v)){
				Yii::$app->db->createCommand($v)->execute();
			}
		}
	}
	
	
	public function actionCheckTablename($modelid = '', $tablename){
		$sql="SHOW TABLES LIKE '{{{%$tablename}}}'";
		$result = Yii::$app->db->createCommand($sql)->queryAll();
		//print_r($result);
		echo ($result==null || $modelid!='') ? 'true' : 'false';
	}
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate()
	{
		$model = self::findModel();
		$models = [];
        if($model->load(Yii::$app->request->post()))
		{
			if($model->save()){
				$models[] = $model;
				$modelids = self::install($models, $model->type, 'create');
				self::actionUpdateCache($modelids);
				$this->OperTips($this->getModelsActionUrl(['index', 'type'=>$model->type]));
			}
		}
		$model->type = $this->models->type;
		return $this->render($this->models->viewFiles['form'],array(
			'model'=>$model,

		));
	}

	/**
	 * 更新数据内容
	 * 模板文件通常为  views/category/_form.php
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionUpdate($modelid)
	{
		$this->models->modelid = $modelid;
		$model= self::findModel($modelid);
		if(isset($_POST['Models']))
		{
			$model->attributes=$_POST['Models'];
			$model->setting = $model->setting ? json_encode($model->setting, JSON_UNESCAPED_UNICODE) : '';
			if($model->save()){
				$this->actionUpdateCache([$modelid]);
				$this->OperTips($this->getModelsActionUrl(['index', 'type'=>$model->type]));
			}
		}
        
		$models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		
		$model->setting = $model->setting ? json_decode($model->setting, true) : array();
		$model->api = $model->api ? json_decode($model->api, true) : array();
		return $this->render($this->models->viewFiles['form'],array(
			'model'=>$model,
			'models' => $models,
			'fields'=> self::listorderFields($modelid),
			'type'=>$this->models->type,

		));
	}
	
	/**
	 * 更新数据内容
	 * 模板文件通常为  views/category/_form.php
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionApi($modelid)
	{
		$this->models->modelid = $modelid;
		$model= self::findModel($modelid);

		if(isset($_POST['Models']))
		{
			
			$data['api'] = json_encode($_POST['Models']['api'], JSON_UNESCAPED_UNICODE);
			Yii::$app->db->createCommand()->update($this->models->models_table, $data, 'modelid = '.$modelid)->execute();
			
			$this->actionUpdateCache([$modelid]);
			
			$function = array();
            foreach(['list', 'view', 'create', 'update'] as $k=>$v){
				if (isset($_POST['Models']['api'][$v]['fields'])) foreach($_POST['Models']['api'][$v]['fields'] as $kk=>$vv){
					$function[$vv] = $_POST['Models']['api']['function'][$vv];
					
				}
				if (isset($_POST['Models']['api']['function']['@callback'][$v])){
					$function[$v]['Callback'] = $_POST['Models']['api']['function']['@callback'][$v];
				}
				
			}
			$this->createSubmoduleExtend('Api', $_POST['Models']['tablename'], $function);
			$this->OperTips($this->getModelsActionUrl(['index', 'type'=>$model->type]));
			
		}
        
		$models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		$submodule_model = Yii::$app->FileCache->get('submodule_model');
		//print_r($submodule_model);
		
		$model->api = $model->api ? json_decode($model->api, true) : array();
		return $this->render($this->getViewFiles('api'),array(
			'model'=>$model,
			'models' => $models,
			'submodule_model' => $submodule_model,
			'fields'=> self::listorderFields($modelid),
			'type'=>$this->models->type,

		));
	}
/**
	 * 更新数据内容
	 * 模板文件通常为  views/category/_form.php
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionApiDocument($modelid)
	{
		$this->models->modelid = $modelid;
		$model= self::findModel($modelid);
		$this->models = Yii::$app->FileCache->get('submodule_model_'.$this->models->modelid);
		foreach($this->models['fields'] as $k=>$v){
			$this->models['fields'][$v['field']] = $v;
			
		}
		$model->api = $model->api ? json_decode($model->api, true) : array();
		return $this->render($this->models->viewFiles['api-document'],array(
			'model'=>$model,
			'type'=>$this->models->type,
			'modelstype'=>$this->modelstype,
		));
	}
    public function apiUrl($route){
		$url = Yii::$app->urlManager->createAbsoluteUrl($route);
		
		$url = str_replace(['submodule'], ['api', 'submodule'], $url);
		
		return $url;
	}

	/**
	 * 删除某一条数据
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionDelete($modelid)
	{
		$model = $this->findModel($modelid);
		Models::updateAll(['deleted'=>1], ['modelid'=>$modelid]);
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax'])){
			$this->OperTips($this->getModelsActionUrl(['index']));
		}
	}
    
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch()
	{
        $ids = isset($_POST['checked_catid']) ? $_POST['checked_catid'] : NULL;
        if ($ids){
            if (isset($_POST['batch_delete'])){
                Models::updateAll(['deleted'=>1], ['modelid'=>$ids]);
                //$backurl = $_SERVER['HTTP_REFERER'];
                $backurl = $this->getModelsActionUrl(['index']);  //跳转到控制器index方法
				$this->renderPartial('//_return/jump',array(
					'backurl'=>$backurl,
					'type'=> '',
				));
                exit();
            }
        }
	}

	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionIndex(){

		$sql="SELECT * FROM `{$this->models->models_table}` where `type` = '{$this->models->type}' and `isdefault`!=-1 and `deleted` = 0";
		if (isset($_POST['keyword'])){
			$sql .= " and (title like '%".$_POST['keyword']."%')";
		}
		$sql .= " order by modelid desc";
        $module = Module::find()->where(['module' => $this->models->type])->one();
        return $this->render(
		$this->models->viewFiles['index'],
		array_merge(YiiMobo::pageRows($sql), ['module'=> $module, 'type'=>$this->models->type]));
	}
    /**
     * 更改状态设置
     * 
     */
    public function actionFieldStatus($fieldid, $field = 'status', $status) {
        $sql = "update {$this->models->field_table} set `$field` = $status where fieldid = '$fieldid'";
        Yii::$app->db->createCommand($sql)->query();
		
    }
	
	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionField($modelid){

		$sql="SELECT * FROM {$this->models->field_table} where modelid = $modelid";
		$sql .= " order by listorder asc,fieldid asc";
		return $this->render($this->models->viewFiles['field'], array_merge(YiiMobo::pageRows($sql), ['modelid'=>$modelid]));
		
	}
	
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionFieldBatch(){
        $ids = isset($_POST['checked_fieldid']) ? $_POST['checked_fieldid'] : NULL;
		$tips = '';
		$backurl = $_SERVER['HTTP_REFERER'];
        if ($ids){
            if (isset($_POST['batch_delete'])){
                ModelsField::model()->deleteByPk($ids);
                
            }
			
        }else if(isset($_POST['batch_listorder'])){
			if ($_POST['listorder']) foreach($_POST['listorder'] as $id=>$listorder){
				
				 ModelsField::updateAll(['listorder'=>intval($listorder)], ['fieldid'=>$id]);
			}
			
		}
        $this->actionUpdateCache([$_POST['modelid']]);
		$this->OperTips($backurl);
		exit();
	}
	
	//数据库添加字段
	public function alterField($modelid, $models){
		if ($models->primarytable == 2) return false;
		$sql="SELECT * FROM {$this->models->models_table} where modelid = $modelid";
		$model= Yii::$app->db->createCommand($sql)->queryOne();
		$tablename = $models->primarytable == 1 ? $model['tablename'] : $model['tablename'].'_data';
		$models->setting = json_decode($models->setting, true);
		//检查副表是否存在
		if ($models->primarytable == 0){
			$liketablename = Yii::$app->db->tablePrefix.$tablename;
			if(!Yii::$app->db->createCommand("SHOW TABLES LIKE '{$liketablename}'")->queryOne()){
				$model = Yii::$app->FileCache->get('submodule_model_'.$modelid);
				$primarykey = $model['primarykey'];
		
				Yii::$app->db->createCommand()->createTable("{{%$tablename}}", [
					primarykey => "int(11) unsigned NOT NULL default '0'",
				],'ENGINE InnoDB DEFAULT CHARSET utf8')->execute();
			}
		}
	    $sql = "alter table {{%$tablename}} add `$models->field` $models->fieldtype";
		$sql .= $models->fieldlength ? "($models->fieldlength)" : "";
		$sql .= $models->setting['defaultvalue'] ? " default '".$models->setting['defaultvalue']."'" : ""; 
		$aa = " not Null";
		Yii::$app->db->createCommand($sql)->execute();
	}
	/**
	 * 新建字段
	 */
	public function actionCreateField($modelid = '', $fieldid = ''){
		$model = self::ModelsField($fieldid);
		if(isset($_POST['Field'])){
			
			$model->attributes=$_POST['Field'];
			$model->setting = json_encode($model->setting, JSON_UNESCAPED_UNICODE);
			$model->param = json_encode($model->param, JSON_UNESCAPED_UNICODE);
			if($model->save()){
				self::actionUpdateCache([$model->modelid]);
				self::alterField($model->modelid, $model);
				$backurl = $this->getModelsActionUrl(['field', 'modelid'=> $model->modelid]);
				$this->OperTips($backurl);
			}
		}
		
		$formtype = $model->formtype;
		$param = json_decode($model->param, true);
        $models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		return $this->render($this->models->viewFiles['field_form'],array(
			'model'=>$model,
			'models'=> $models,
			'modelid'=> $modelid
			
		));
	}
	/**
	 * 修改字段

	 * 
	 */
	public function actionUpdateField($modelid = '', $fieldid){
		$model = self::ModelsField($fieldid);
		
		if(isset($_POST['Field'])){
			$model->attributes=$_POST['Field'];
			$model->setting = $model->setting ? json_encode($model->setting, JSON_UNESCAPED_UNICODE) : '';

			$model->param = $model->param ? json_encode($model->param, JSON_UNESCAPED_UNICODE) : '';
			if($model->save()){
				self::actionUpdateCache([$model->modelid]);
				$backurl = $this->getModelsActionUrl(['field', 'modelid'=> $model->modelid]);
				$this->OperTips($backurl);
			}
		}
		
		$formtype = $model->formtype;
		
        $model->setting = $model->setting ? json_decode($model->setting, true) : array();
		$model->param = $model->param ? json_decode($model->param, true) : array();  
		return $this->render($this->models->viewFiles['field_form'],array(
			'model'=>$model,
			'modelid'=> $modelid,
			//'param' => self::actionFormfield($formtype, $model->param, true)
		));
	}
	
	
	
	
	/**
	* 更新栏目缓存
	*
	*
	*/
	public function actionUpdateCache($modelids = false, $goback = false){
		if (!$modelids){
			$modelids = array_keys(Yii::$app->FileCache->get('submodule_model'));
			//print_r($modelids);
		}
		$tablename = $this->models->models_table;
		$modelids = is_array($modelids) ? $modelids : [$modelids];
		foreach($modelids as $modelid){
			$sql="SELECT * FROM $tablename where modelid = $modelid";
			$data['models'] = Yii::$app->db->createCommand($sql)->queryOne();
			
			$data['models']['setting'] = $data['models']['setting'] ? json_decode($data['models']['setting'] ,true) : array();
			$data['models']['param'] = $data['models']['param'] ? json_decode($data['models']['param'] ,true) : array();
			$data['models']['api'] = $data['models']['api'] ? json_decode($data['models']['api'] ,true) : array();
			$sql="SELECT * FROM {$this->models->field_table} where modelid = $modelid order by listorder asc, fieldid asc";
			$data['fields'] = Yii::$app->db->createCommand($sql)->queryAll();
			
			$fields = array();
			$allowinput_fields = array(); 
			$function = array();
			$data['primarykey'] = 'id';
			$data['data_tablename'] = "{{%{$data['models']['tablename']}_data}}";
			if (!Yii::$app->db->createCommand("SHOW TABLES LIKE '{$data['data_tablename']}'")->queryOne()){
				$data['data_tablename'] = false;
			}
			
	
			foreach($data['fields'] as $k=>$v){
				if ($v['formtype'] == 'primarykey') {
					$data['primarykey'] = $v['field'];//主键
				}
				
				$v['setting'] = $v['setting'] ? json_decode($v['setting'] ,true) : array();
				$v['param'] = $v['param'] ? json_decode($v['param'] ,true) : array();
				$v['api'] = $v['api'] ? json_decode($v['api'] ,true) : array();
				$fields[$v['fieldid']] = $v;
				if ($v['allowinput']) $allowinput_fields[] = $v['field'];
				$function[$v['field']][0] = $v['fieldid'];
				if (isset($v['param']['actionfunction']) && $v['param']['actionfunction']) foreach($v['param']['actionfunction'] as $kk=>$vv){
					$function[$v['field']][$kk] = $vv;
				}
				
				
			}
			$data['fields'] = $fields;
			$data['allowinput_fields'] = $allowinput_fields;
			$c = Yii::$app->FileCache->set('submodule_model_'.$modelid, $data);

			$this->createSubmoduleExtend('Backend', $data['models']['tablename'], $function);
	
			
		}

		$data = [];
		$sql="SELECT * FROM {$this->models->models_table} where `deleted` = 0";
		foreach(Yii::$app->db->createCommand($sql)->queryAll() as $v){
			$v['setting'] = [];
			$v['param'] = [];
			$v['api'] = [];
			$data[$v['modelid']] = $v;
		};
		Yii::$app->FileCache->set('submodule_model', $data);
		if ($goback) $this->OperTips();
        //echo $function;
		//exit;
		
	}
	
	public function actionFields($modelid){
		$models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		echo json_encode($models['fields'], JSON_UNESCAPED_UNICODE);
		
	}
	
	public function actionFormfield($modelid, $fieldid, $formtype, $return = false){
		$path = substr($formtype, 0, 1 ) == '_' ? 'common' : 'submodule';
		$template = "@{$path}/widgets/$formtype/views/_field";
		$model = self::ModelsField($fieldid);
		$model->param = $model->param ? json_decode($model->param, true) : array();  
		$data['form'] = $this->render($template,array(
		    'fieldid'=>$fieldid,
			'formtype'=>$formtype,
			'param' => $model->param
		), true);
		if ($return){
		     return $data;
		}else{
			echo json_encode($data, JSON_UNESCAPED_UNICODE);
		}
		
	}
	
    /**
	* 后台首页字段显示排序
	*/
    public function listorderFields($modelid){
		$fields = array();
		$models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		$listorder = isset($models['models']['setting']['index']['listorder']) ? $models['models']['setting']['index']['listorder'] : array();
	    foreach($models['fields'] as $k=>$v){
			//echo $k.',';
			if(!in_array($k, $listorder)) $fields[$k] = $v;
		}
			
		$fields = $listorder ? array_flip($listorder) + $fields : $models['fields'];
		return $fields;
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Category the loaded model
	 * @throws CHttpException
	 */
    protected function findModel($id = '')
    {
		$model =$id ? Models::findOne($id) : new Models;
        if ( $model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	public function ModelsField($id = null)
	{
		$model = $id ? ModelsField::findOne($id) : new ModelsField();
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	

	/**
	 * Performs the AJAX validation.
	 * @param Category $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::$app->end();
		}
	}
}
